<?php
/**
 * Business.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-19
 * Time: 11:09
 */

namespace App\Http\Controllers\Api\BaseData;


use App\Http\Controllers\Base;
use App\Tables;
use Illuminate\Support\Facades\Log;
use App\Exceptions\RunException;

class Business extends Base
{
    public function getList()
    {
        $name = $this->request->get('name', '');
        $id   = $this->request->get('id');
        $id = is_array($id) ? (array) $id : (empty($id) ? null : [(int) $id]);
        $t = Tables\Business::query();
        if(!empty($id)) {
            $t->whereIn('id', $id);
        }
        if(!empty($name)) {
            $all = $t->where(['name' => $name])->orWhere('name', 'like', "%{$name}%")->get();
        } else {
            $all = $t->get();
        }

        if($all->isEmpty()) {
            return $this->responseSuccess();
        }
        $r = [];
        foreach($all as $item) {
            $postPrintIDList = $item->postPrints;
            $ppList = [];
            foreach($postPrintIDList as $pp) {
                $ppInfo = $pp->info;
                if(!empty($ppInfo)) {
                    $ppList[] = [
                        'id' => $ppInfo['id'],
                        'name' => $ppInfo['name']
                    ];
                }
            }

            $consumableIDList = $item->consumables;
            $cList = [];
            foreach($consumableIDList as $cc) {
                $ccInfo = $cc->info;
                if(!empty($ccInfo)) {
                    $cList[] = [
                        'id' => $ccInfo['id'],
                        'name' => $ccInfo['name']
                    ];
                }
            }
            $priceNoticeList = $item->priceNotices;
            $pnList = [];
            foreach($priceNoticeList as $pn) {
                $pnList[] = [
                    'type' => $pn['type'],
                    'symbol' => $pn['symbol'],
                    'number' => $pn['number'],
                    'price'  => $pn['price']
                ];
            }

            $r[] = [
                'id' => $item['id'], 'name' => $item['name'], 'pyCode' => $item['py_code'],
                'unit' => $item['unit'], 'countType' => ['id'=>0, 'countType' => $item['count_type'], 'name' => ''],
                'postPrint' => $ppList,
                'consumable' => $cList,
                'priceNotice' => $pnList
            ];
        }

        return $this->responseSuccess($r);
    }

    public  function get()
    {
        $id = (int) $this->request->get('id', 0);
        if($id <= 0) {
            return $this->responseSuccess();
        }
        $business = Tables\Business::where('id', $id)->first();
        if(empty($business)) {
            return $this->responseSuccess();
        }

        $postPrintIDList = $business->postPrints;
        $ppList = [];
        foreach($postPrintIDList as $pp) {
            $ppInfo = $pp->info;
            if(!empty($ppInfo)) {
                $ppList[] = $ppInfo['id'];
            }
        }

        $consumableIDList = $business->consumables;
        $cList = [];
        foreach($consumableIDList as $cc) {
            $ccInfo = $cc->info;
            if(!empty($ccInfo)) {
                $cList[] = $ccInfo['id'];
            }
        }
        $priceNoticeList = $business->priceNotices;
        $pnList = [];
        foreach($priceNoticeList as $pn) {
            $pnList[] = [
                'type' => $pn['type'],
                'symbol' => $pn['symbol'],
                'number' => $pn['number'],
                'price'  => $pn['price']
            ];
        }
        return $this->responseSuccess([
            'id' => $business['id'], 'name' => $business['name'], 'pyCode' => $business['py_code'],
            'unit' => $business['unit'], 'countType' => ['id'=>0, 'countType' => $business['count_type'], 'name' => ''],
            'postPrint' => $ppList,
            'consumable' => $cList,
            'priceNotice' => $pnList
        ]);
    }

    public  function add()
    {
        $name       = $this->request->post('name');
        $pyCode     = $this->request->post('pyCode');
        $countType  = (int) $this->request->post('countType', 0);
        $unit       = $this->request->post('unit');
        $postPrint  = (array) $this->request->post('postPrint', []);
        $consumable = (array) $this->request->post('consumable', []);
        $priceNotice = (array) $this->request->post('priceNotice', []);

        if(empty($name)) {
            return $this->responseFail('业务名称不能为空');
        }
        if($countType <= 0) {
            return $this->responseFail('请选择计价方式');
        }
        if(empty($unit)) {
            return $this->responseFail('请输入业务单位');
        }
        $addTime = time();
        \DB::beginTransaction();
        try {
            $bid = (int) Tables\Business::insertGetId([
                'name' => $name,
                'py_code' => $pyCode,
                'unit' => $unit,
                'count_type' => $countType,
                'add_time' => $addTime
            ]);
            if($bid<=0) { throw new RunException('写入失败(1)');}
            $insertData = [];
            foreach($consumable as $cid) {
                $insertData[] = [
                    'bid' => $bid,
                    'cid' => $cid
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\BusinessConsumable::insert($insertData);
                if(!$ok) { throw new RunException('写入失败(2)');}
            }

            $insertData = [];
            foreach($postPrint as $pid) {
                $insertData[] = [
                    'bid' => $bid,
                    'pid' => $pid
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\BusinessPostPrint::insert($insertData);
                if(!$ok) { throw new RunException('写入失败(3)');}
            }

            $insertData = [];
            foreach ($priceNotice as $notice) {
                $insertData[] = [
                    'bid' => $bid,
                    'type' => $notice['type'],
                    'symbol' => $notice['symbol'],
                    'number' => $notice['number'],
                    'price' => $notice['price'],
                    'add_time' => $addTime
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\BusinessPriceNotice::insert($insertData);
                if(!$ok) { throw new RunException("写入失败(4)");}
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库出错');
        }
        return $this->responseSuccess();
    }

    public  function update()
    {
        $id         = (int) $this->request->post('id', 0);
        $name       = $this->request->post('name');
        $pyCode     = $this->request->post('pyCode');
        $countType  = (int) $this->request->post('countType', 0);
        $unit       = $this->request->post('unit');
        $postPrint  = (array) $this->request->post('postPrint', []);
        $consumable = (array) $this->request->post('consumable', []);
        $priceNotice = (array) $this->request->post('priceNotice', []);

        if($id <= 0) {

            return $this->responseFail('查询不到数据！');
        }
        if(empty($name)) {
            return $this->responseFail('业务名称不能为空');
        }
        if($countType <= 0) {
            return $this->responseFail('请选择计价方式');
        }
        if(empty($unit)) {
            return $this->responseFail('请输入业务单位');
        }
        $addTime = time();
        \DB::beginTransaction();
        try {
            $business = Tables\Business::where(['id' => $id])->first();
            $bid = $business['id'];
            $business['name'] = $name;
            $business['py_code'] = $pyCode;
            $business['unit'] = $unit;
            $business['count_type'] = $countType;
            $ok = (bool) $business->save();

            if(!$ok) { throw new RunException('写入失败(1)');}

            $insertData = [];
            foreach($consumable as $cid) {
                $insertData[] = [
                    'bid' => $bid,
                    'cid' => $cid
                ];
            }
            if(!empty($insertData)) {
                Tables\BusinessConsumable::where(['bid' => $bid])->delete();
                $ok = (bool) Tables\BusinessConsumable::insert($insertData);
                if(!$ok) { throw new RunException('写入失败(2)');}
            }

            $insertData = [];
            foreach($postPrint as $pid) {
                $insertData[] = [
                    'bid' => $bid,
                    'pid' => $pid
                ];
            }
            if(!empty($insertData)) {
                Tables\BusinessPostPrint::where(['bid' => $bid])->delete();
                $ok = (bool) Tables\BusinessPostPrint::insert($insertData);
                if(!$ok) { throw new RunException('写入失败(3)');}
            }

            $insertData = [];
            foreach ($priceNotice as $notice) {
                $insertData[] = [
                    'bid' => $bid,
                    'type' => $notice['type'],
                    'symbol' => $notice['symbol'],
                    'number' => $notice['number'],
                    'price' => $notice['price'],
                    'add_time' => $addTime
                ];
            }
            if(!empty($insertData)) {
                Tables\BusinessPriceNotice::where(['bid' => $bid])->delete();
                $ok = (bool) Tables\BusinessPriceNotice::insert($insertData);
                if(!$ok) { throw new RunException("写入失败(4)");}
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库出错');
        }
        return $this->responseSuccess();
    }

    public function del()
    {
        $id = (int) $this->request->post('id', 0);
        if($id <= 0) {
            return $this->responseFail('查询不到数据');
        }
        $business = Tables\Business::where(['id' => $id])->first();
        if(empty($business)) {
            return $this->responseFail('未到找数据！');
        }
        \DB::beginTransaction();
        try{
            $bid = $business['id'];
            Tables\BusinessPriceNotice::where(['bid' => $bid])->delete();
            Tables\BusinessPostPrint::where(['bid' => $bid])->delete();
            Tables\BusinessConsumable::where(['bid' => $bid])->delete();
            $ok = (bool) $business->delete();
            if(!$ok) {
                throw new RunException('删除失败！');
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            Log::error($e->getMessage());
            return $this->responseFail('数据库错误！');
        }
        return $this->responseSuccess();
    }
}